package com.shyroke.daydayzhuanweb.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.shyroke.daydayzhuanapi.constant.ProjectConst;
import com.shyroke.daydayzhuanapi.dto.AppDto;
import com.shyroke.daydayzhuanapi.dto.AppSearchRequest;
import com.shyroke.daydayzhuanapi.dto.UserMain;
import com.shyroke.daydayzhuanapi.entity.AppEntity;
import com.shyroke.daydayzhuanapi.entity.AppLabelEntity;
import com.shyroke.daydayzhuanapi.entity.LabelEntity;
import com.shyroke.daydayzhuandao.respository.AppLabelRepository;
import com.shyroke.daydayzhuandao.respository.AppRepository;
import com.shyroke.daydayzhuandao.respository.LabelRepository;
import com.shyroke.daydayzhuansvc.service.impl.AppService;
import com.shyroke.daydayzhuansvc.service.impl.OSSService;
import com.shyroke.daydayzhuansvc.util.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 类名 ：系统管理controller
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2019/2/21 12:49
 */
@Controller
@RequestMapping(value = "/admin/app")
public class AppController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AppService appService;
    @Autowired
    private AppRepository appRepository;
    @Autowired
    private OSSService ossService;
    @Autowired
    private AppLabelRepository appLabelRepository;
    @Autowired
    private LabelRepository labelRepository;

    /**
     * 跳转到网站地图
     * @param model
     * @return
     */
    @RequestMapping(value = "listView")
    public ModelAndView siteMap (ModelAndView model){
        model.setViewName("admin/projectInvate/listView");
        return  model;
    }

    /**
     * 获取项目邀请列表
     * @return
     */
    @RequestMapping(value = "applist")
    @ResponseBody
    public TabelData<AppDto> getAppPage(Page page, AppSearchRequest request){
        return appService.getProjectInvateList(page,request);
    }

    /**
     * 跳转到新增免费项目页面
     * @param model
     * @return
     */
    @RequestMapping(value = "addView")
    public ModelAndView freeToAdd(ModelAndView model,String source,Integer projectId){
        model.addObject("source",source);
        model.addObject("projectId",projectId);
        model.setViewName("admin/projectInvate/add");

        return model;
    }

    /**
     * 保存免费项目
     * @param app
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public R free_project_save(@RequestBody AppDto app, HttpSession session){
        UserMain user = (UserMain)session.getAttribute("user");
        Date currenDate = new Date();

        if(user == null){
            return R.error("登录超时！请重新登录");
        }

        app.setCreateTime(currenDate); //设置创建时间
        app.setDownCount(0);//阅读数量
        app.setOffline(Integer.valueOf(ProjectConst.UNOFFLINE)); //默认未下架
        app.setUpdateTime(currenDate);
        app.setCreateId(user.getId());

        String title = app.getTitle();
        Document document = Jsoup.parse(app.getContent());
        Elements elements = document.select("img");
        if(elements!=null&&elements.size()>0){
            for(int i= 0;i<elements.size();i++){
                Element element = elements.get(i);
                element.attr("alt",title+"  第"+(i+1)+"张");
            }
            app.setContent(document.html());
        }
        try {
            appService.save(app);
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            return R.error("保存失败，原因="+e.getMessage());
        }
        return R.ok("保存成功！");
    }

    /**
     * 编辑页面
     * @param model
     * @return
     */
    @RequestMapping(value = "edit/{id}")
    public ModelAndView descAndEdit(ModelAndView model, @PathVariable("id")Integer appId){

        AppDto app = appService.findById(appId);

        if(!StringUtils.isEmpty(app.getCover())){
            app.setCover(ossService.getImgUrl(app.getCover()));
        }
        if(!StringUtils.isEmpty(app.getInviteImg())){
            app.setInviteImg(ossService.getImgUrl(app.getInviteImg()));
        }
        if(!StringUtils.isEmpty(app.getWithdraw())){
            app.setWithdraw(ossService.getImgUrl(app.getWithdraw()));
        }

        //获取关键字
        List<AppLabelEntity> appLabelList = appLabelRepository.findByAppIdOrderByIdDesc(app.getId());
        String keywords = "";
        if(CollectionUtil.isNotEmpty(appLabelList)){
            List<LabelEntity> labelList = appLabelList.stream().map(e -> {
                Optional<LabelEntity> optionalLabelEntity = labelRepository.findById(e.getLabelId());
                if(optionalLabelEntity.isPresent()){
                    return optionalLabelEntity.get();
                }
                return null;
            }).collect(Collectors.toList());
            keywords = labelList.stream().map(l -> l.getLabelName()).collect(Collectors.joining(","));
        }

        model.addObject("keywords",keywords);
        model.addObject("app",app);
        model.setViewName("admin/projectInvate/edit");

        return model;
    }

    /**
     * 修改app信息
     * @param app
     * @return
     */
    @RequestMapping(value = "update")
    @ResponseBody
    public R update(@RequestBody AppDto app, HttpSession session){

        if(app.getId() == null){
            return R.error("id不能为空！");
        }
        //过滤图片地址htttps/http+oss-cn-shenzhen.aliyuncs.com开头
        app.setCover(CommonUtil.deleteOSSImgPre(app.getCover()));
        app.setInviteImg(CommonUtil.deleteOSSImgPre(app.getInviteImg()));
        app.setWithdraw(CommonUtil.deleteOSSImgPre(app.getWithdraw()));

        //防止图片地址的字符被转义，比如a(1).png会被转义成a%281%29.png,导致显示错误。
        try {
            if(app.getCover()!=null){
                app.setCover(URLDecoder.decode(app.getCover(),"utf-8"));
            }
            if(app.getContent()!=null){
                String content = app.getContent();
                content = content.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
                content = content.replaceAll("\\+", "%2B");
                app.setContent(content);
                app.setContent(URLDecoder.decode(app.getContent(),"utf-8"));
            }
        }catch (Exception e){
            logger.info("转义失败，原因="+ExceptionUtil.getMessage(e));
            return R.error("转义失败");
        }

        try {
            app.setUpdateTime(new Date());
            appService.update(app);
        }catch (Exception e){
            logger.info(ExceptionUtil.getMessage(e));
            return R.error("修改失败，原因="+e.getMessage());
        }
        return R.ok("修改成功！");
    }


    /**
     * 上下架
     * @return
     */
    @RequestMapping(value = "offline")
    @ResponseBody
    public R offline(@RequestParam Integer id,@RequestParam Integer offline){
        Optional<AppEntity> optionalAppEntity = appRepository.findById(id);
        if(!optionalAppEntity.isPresent()){
            return R.error("app不存在！");
        }
        AppEntity app = optionalAppEntity.get();
        app.setOffline(offline);
        appRepository.save(app);
        return R.ok("保存成功！");
    }
}
